package cn.wsalix.shiro.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.anlaser.utils.FastJsonMapper;
import cn.wsalix.admin.form.UserForm;
import cn.wsalix.shiro.token.CaptchaToken;

/**
 * @author jskyme
 * 
 */
public class JsonAuthenticationFilter extends FormAuthenticationFilter {
	private static final Logger logger = LoggerFactory
			.getLogger(JsonAuthenticationFilter.class);
	private String jsonContentType = "application/json;charset=UTF-8";
	private String contentType = "Content-Type";

	/*
	 * 主要是针对登入成功的处理方法。对于请求头是AJAX的之间返回JSON字符串。
	 */
	@Override
	protected boolean onLoginSuccess(AuthenticationToken token,
			Subject subject, ServletRequest request, ServletResponse response)
			throws Exception {
		
		return false;
	}

	/**
	 * 主要是处理登入失败的方法
	 */
	@Override
	protected boolean onLoginFailure(AuthenticationToken token,
			AuthenticationException e, ServletRequest request,
			ServletResponse response) {
		logger.info(token.getPrincipal() + ":" + token.getCredentials()
				+ " login Failure!" + e.getClass().getSimpleName());
		
		
		return false;
	}

	/**
	 * 所有请求都会经过的方法。
	 */
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		// showPara(request,response);
		return super.onAccessDenied(request, response);
	}

	/*
	 * loginWay 登陆方式：1，手机号密码登陆 2.第三方登陆 thirdPartyType
	 * 第三方登陆类型（1，微信，2，QQ，3，新浪微博）注第三方登陆用 thirdUserId
	 * 第三方账号ID(1,微信的uuionId，2，QQ的openId，3，新浪微博的uid)注第三方登陆用 custNickName 第三方客户昵称
	 * 注：第三方登陆用 custHeadpic 第三方客户头像 注：第三方登陆用 custSex 第三方客户昵称 注：第三方登陆用 custPhone
	 * 客户手机号 注：手机号登陆用 custPassword 客户密码 注：手机号登陆用 (non-Javadoc)
	 * 
	 * @see
	 * org.apache.shiro.web.filter.authc.FormAuthenticationFilter#createToken
	 * (javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	protected AuthenticationToken createToken(ServletRequest request,
			ServletResponse response) {

		CaptchaToken upcToken = null;
		BufferedReader br;
		try {
			br = new BufferedReader(new InputStreamReader(
					(ServletInputStream) request.getInputStream()));

			String line = null;
			StringBuilder strBuff = new StringBuilder();
			while ((line = br.readLine()) != null) {
				strBuff.append(line);
			}
			logger.info(strBuff.toString());
			UserForm userForm = FastJsonMapper.fromJson(strBuff.toString(),
					UserForm.class);
			upcToken = new CaptchaToken();
			upcToken.setUsername(userForm.getUsername());
			upcToken.setPassword(userForm.getPassword().toCharArray());
			upcToken.setRememberMe(true);
			String host = getHost(request);
			upcToken.setHost(host);
			logger.info(userForm.getUsername() + ":" + userForm.getPassword()
					+ " login on(" + host + ")!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return upcToken;
	}
}
